package com.example.controller;


import com.example.anno.Login;
import com.example.anno.Logout;
import com.example.entity.*;
import com.example.service.UserService;
import com.example.utils.JwtUtils;
import com.example.utils.RedisCache;
import com.example.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@Slf4j
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 用户注册
     * @param user 用户实体信息
     * @return 注册成功或失败
     */
    @PostMapping("/register")
    public Result<User> register(@RequestBody User user){
        log.info("用户注册信息");
        String email = user.getEmail();
        if (userService.emailExist(email) == 1){
            return Result.error("用户邮箱已存在");
        }
        if (userService.usernameExist(user.getUsername())){
            return Result.error("用户名已存在");
        };
        userService.register(user);
        return Result.success();
    }

    /**
     * 用户登录
     * @param user 用户登录信息
     * @return 登录产生的token等信息
     */
    @Login
    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginEntity user){
        log.info("用户登录：{}", user);
        Integer code = userService.login(user);

        //登录成功，生成令牌，下发令牌
        if (code == 1) {
            log.info("登录成功");
            Integer userId = userService.getIdByUsername(user.getUsername());
            Map<String, Object> claim = new HashMap<>();
            claim.put("id", userId);
            claim.put("permission", user.getPermission());
            claim.put("username", user.getUsername());
            String jwt = JwtUtils.generateJwt(claim);

            //把token存储到redis中
            redisCache.setCacheObject(jwt, jwt,12, TimeUnit.HOURS);

            return Result.success(jwt);
        } else if (code == 2) {
            //登录失败，返回错误信息
            log.info("登录失败");
            return Result.error("用户名或密码出错！");
        } else {
            log.info("用户不存在");
            return Result.error("用户不存在");
        }
    }

    /**
     * 登出
     * @return LoginResponse对象
     */
    @Logout
    @PostMapping("/logout")
    public Result<LoginResponse> logout(@RequestHeader("token") String token ){
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userService.logout(token, id);
        return Result.success();
    }
}
